# -*- coding: utf-8 -*-
"""
Created on Thu Aug 30 13:26:42 2018

@author: Who

https://www.weixiang28.com/
微想财经


"""

import requests
import re
from cs import day
from WriteData import writedata
from Tk import genearteMD5


def get_html_text(url):
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Encoding': 'gzip, deflate, br',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Connection': 'keep-alive',
        'Host': 'www.weixiang28.com',
        'Referer': 'https://www.weixiang28.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
    }
    try:
        r = requests.get(url, timeout=30, headers=headers)
        r.raise_for_status()
        r.encoding = r.apparent_encoding
        return r.text
    except Exception as e:
        print(e)
        return None


def get_dates_sy(url):
    text = get_html_text(url)
    if not text:
        return None
    text = eval(text)
    dates = [date['add_time'][:10] for date in text]
    return dates


def get_dates_kx(url):
    text = get_html_text(url)
    if not text:
        return None
    regex = re.compile(r'<div class="time"> ([\s\S]*?) \d{2}:\d{2}:\d{2}</div>')
    dates = re.findall(regex, text)
    return dates


def count_process_sy():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        url = 'https://www.weixiang28.com/p/index/get_dakashuo_ajax/p/{}'
        url = url.format(a)
        dates = get_dates_sy(url)
        if not dates:
            break
        print('----微想财经区块链大咖获取第{}页----'.format(a))
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def count_process_kx():
    d1 = 0
    d2 = 0
    d3 = 0
    d4 = 0
    a = 1
    while 1:
        url = 'https://www.weixiang28.com/newsflashlist?page={}'
        url = url.format(a)
        dates = get_dates_kx(url)
        if not dates:
            break
        print('----微想财经快讯获取第{}页----'.format(a))
        for date in dates:
            s = day(date)
            if s == 0:
                d1 += 1
            elif s == 1:
                d2 += 1
            elif s == 2:
                d3 += 1
            else:
                d4 += 1
        a += 1
        if d4 > 0:
            break
    return (d1, d2, d3)


def main():
    u = '微想财经'
    t1 = count_process_kx()
    t2 = count_process_sy()
    tk = genearteMD5(u)
    D = {tk: {"name": u, "today": t1[0] + t2[0], "yesterday": t1[1] + t2[1], "frontday": t1[2] + t2[2]}}
    writedata(D)
    return D


if __name__ == '__main__':
    print(main())
